
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'StrSub_pipe' })

/**
 * 对超过18个长度的中英文字符进行截断
 */
export class StrSub_pipe implements PipeTransform {
  transform(value: string): string {
    if (!value) return value;
    var str = value;
    if (typeof value !== 'string') {
      throw new Error('Invalid pipe argument for WelcomePipe');
    }
    var len = this.strlen(value);
    if (len > 18) {
      str = str.substr(0, 15) + '...'
    }
    return str;

  }

  /**
   * 
   * @param str 判断中英文字符长度
   */
  strlen(str) {
    var len = 0;
    for (var i = 0; i < str.length; i++) {
      var c = str.charCodeAt(i);
      //单字节加1 
      if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
        len++;
      }
      else {
        len += 2;
      }
    }
    return len;
  }





} 